<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>添加多边形</title>
    <link rel="stylesheet" href="../v6.4.3/css/ol.css">
    <link rel="stylesheet" href="css/common.css">
  </head>
  <body>
    <div id="map" style="height: 90%;"></div>
    <label>Shape type &nbsp;</label>
    <select name="" id="type">
      <option value="">Select</option>
      <option value="Point">Point</option>
      <option value="LineString">LineString</option>
      <option value="Polygon">Polygon</option>
      <option value="Circle">Circle</option>
      <option value="Square">Square</option>
      <option value="Box">Box</option>
      <option value="None">None</option>
    </select>

    <script src="../v6.4.3/build/ol.js"></script>
    <script>
      
      // DOM对象变量
      let typeSelect = document.getElementById('type')

      // ol.Map 的各种参数对象
      let vectorSource = new ol.source.Vector()
      let vectorLayer = new ol.layer.Vector({
        source: vectorSource
      })
      let mapLayer = new ol.layer.Tile({
        source: new ol.source.OSM()
      })
      let mapView = new ol.View({
        projection: 'EPSG:3857',
        center: [0, 0],
        zoom: 0
      })
      
      // 创建 ol.Map 实例
      let map = new ol.Map({
        target: 'map',
        layers: [mapLayer, vectorLayer],
        view: mapView
      })

      // 事件绑定
      typeSelect.addEventListener('change', () => {
        map.removeInteraction(draw)
        addInteraction()
      })

      //
      let draw
      function addInteraction() {
        let type = typeSelect.value;
        if (type && type !== 'None') {
          let geometryFunction;
          switch (type) {
            case 'Square':
              type = 'Circle';
              geometryFunction = ol.interaction.Draw.createRegularPolygon(4);
              break;
            case 'Box':
              type = 'Circle';
              geometryFunction = ol.interaction.Draw.createBox();
              break;
          }
          //初始化绘图控件
          draw = new ol.interaction.Draw({
            source: vectorSource,
            type: type,
            geometryFunction: geometryFunction
          })
          map.addInteraction(draw)
        }
      }

      // source -- 绘制的集合图形将会被存储到这个地图源中
      // type -- 要绘制的几何图形类型，可以设置为：Point、LineString、LinearRing、MultiPoint、MultiLineString、
      //         MultiPolygon、GeometryCollection、Circle
      // geometryFunction -- 这个参数可以比较自由地设置要绘制的几何图形的形状，比如这个这个示例中使用
      //                     createBox() 和 createRegularPolygon() 这两个函数来生成特定的图形函数，
      //                     以代替绘制圆，但使用这两函数必须将 type 参数设置为 'Circle'

    </script>
  </body>
</html>